package org.example.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import lombok.extern.slf4j.Slf4j;
import org.example.mapper.MenuMapper;
import org.example.mapper.PermissionMapper;
import org.example.mapper.UserMapper;
import org.example.model.table.Menu;
import org.example.model.table.Permission;
import org.example.model.table.User;
import org.example.service.MenuService;
import org.example.util.JwtUtils;
import org.example.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Slf4j
@Service
public class MenuServiceImpl implements MenuService {

    @Autowired
    UserMapper userMapper;
    @Autowired
    MenuMapper menuMapper;

    @Autowired
    PermissionMapper permissionMapper;

    @Override
    public Result getMenus(String token) {
        User userInfo = JwtUtils.toObj(token, User.class);
        LambdaQueryWrapper<User> userQueryWrapper = new LambdaQueryWrapper<>();
        userQueryWrapper.eq(User::getAccount, userInfo.getAccount());
        // select * from menu m inner join permission p on m.id = p.menu_id where p.role_id=?;
        if (userMapper.selectOne(userQueryWrapper)!=null){
            MPJLambdaWrapper<Menu> menuMPJLambdaWrapper = new MPJLambdaWrapper<>();
            menuMPJLambdaWrapper
                    .selectAll(Menu.class)
                    .innerJoin(Permission.class,Permission::getMenuId,Menu::getId)
                    .eq(Permission::getRoleId,userInfo.getRoleId());
            List<Menu> menus = menuMapper.selectList(menuMPJLambdaWrapper);
            return Result.ok().data("list", menus);
        }
        return Result.error().data("list", null);
    }

    @Override
    public Result getAll(String token) {
        User userInfo = JwtUtils.toObj(token, User.class);
        LambdaQueryWrapper<User> userQueryWrapper = new LambdaQueryWrapper<>();
        userQueryWrapper.eq(User::getAccount, userInfo.getAccount());
        // select * from menu m inner join permission p on m.id = p.menu_id where p.role_id=?;
        if (userMapper.selectOne(userQueryWrapper)!=null){
            List<Menu> menus = menuMapper.selectList(null);
            return Result.ok().data("list", menus);
        }
        return Result.error().data("list", null);
    }
}
